package com.service.impl;


import com.entity.Label;
import com.repository.LabelRepository;
import com.service.LabelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;

@Service
@Transactional
public class LabelServicelmpl implements LabelService {
    private static final Logger logger = LoggerFactory.getLogger(com.service.impl.LabelServicelmpl.class);

    @Autowired
    private LabelRepository labelRepository;

    @Override
    public Page<Label> findByPageAndParams(Integer page, Integer size, String labelkey, String orderBy, String sortOrder) {
        Integer Page = page - 1;
        String sortorder = sortOrder.toUpperCase();
        Sort sort = new Sort(Sort.Direction.valueOf(sortorder), orderBy);
        Pageable pageable = PageRequest.of(Page, size, sort);
        if ( labelkey != null ){
            Specification<Label> spec = new Specification<Label>() {
                @Override
                public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//                    Path<Integer> namespaceid = root.get("namespaceid");
                    Path<String> s_labelkey = root.get("labelkey");
                    //Predicate p1 = cb.equal(namespaceid,param.getNamespaceid());
                    Predicate p2 = cb.like(s_labelkey, "%" + labelkey + "%");
//                    Predicate p = cb.and(p2);
                    return p2;
                }};
            return labelRepository.findAll(spec, pageable);
        }
        else {
            return labelRepository.findAll(pageable);
        }
    }
}
